using System;
using System.Linq;
using System.Threading.Tasks;
using Furion.DependencyInjection;
using Furion.EventBus;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Admin.NET.Application.EventBus;

/// <summary>
/// 短信发送消息订阅，类型为2
/// </summary>
public class MessageEventSubscribe : IEventSubscriber, ISingleton, IPrivateDependency
{
	private readonly IServiceProvider _serviceProvider;

	public MessageEventSubscribe(IServiceProvider serviceProvider)
	{
		_serviceProvider = serviceProvider;
	}

	/// <summary>
	/// 发送通知短信
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("2:SendBillNotice")]
	public async Task SendNotice(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		SmsService smsService = scope.ServiceProvider.GetRequiredService<SmsService>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		BillNoticePayload owners = JsonConvert.DeserializeObject<BillNoticePayload>(payload.Data);
		await smsService.SendSms(phoneNumbers: owners.Owners.Select((Owner s) => "+86" + s.PhoneNumber).ToArray(), tenantId: payload.TenantId, phoneNumber: null, type: 2, roomName: null, balanceLimit: null, enddate: owners.EndDate);
	}

	/// <summary>
	/// 短信余额预警
	/// </summary>
	/// <param name="context"></param>
	/// <returns></returns>
	[EventSubscribe("2:SendEarlyWarningNotice")]
	public async Task SendEarlyWarningNotice(EventHandlerExecutingContext context)
	{
		using IServiceScope scope = _serviceProvider.CreateScope();
		SmsService smsService = scope.ServiceProvider.GetRequiredService<SmsService>();
		EventPayload payload = (EventPayload)context.Source.Payload;
		BillNoticePayload gateNotice = JsonConvert.DeserializeObject<BillNoticePayload>(payload.Data);
		if (gateNotice.Owners.Count > 0)
		{
			await smsService.SendSms(phoneNumber: gateNotice.Owners[0].PhoneNumber, tenantId: payload.TenantId, type: 1, roomName: gateNotice.RoomName, balanceLimit: gateNotice.Balance.ToString());
		}
	}
}
